<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom:10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="input"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          node-key="id"
          :expand-on-click-node="false"
          :highlight-current="true"
          default-expand-all
          :data="deups"
          :props="defaultProps"
          @current-change="selectNode"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-if="haenbale('addemployee')" size="mini" type="primary" @click="addemployee">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="exportEmployee">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table
          :data="list"
          style="width: 100%"
        >
          <el-table-column
            prop="staffPhoto"
            label="头像"
            width="80"
          >
            <template v-slot="{row}">
              <el-avatar v-if="row.staffPhoto" :size="30" :src="row.staffPhoto" />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="username"
            label="姓名"
            width="80"
          />
          <el-table-column
            prop="mobile"
            label="手机号"
            sortable
          />
          <el-table-column
            prop="workNumber"
            label="工号"
            sortable
          />
          <el-table-column
            prop="formOfEmployment"
            label="聘用形式"
          >
            <template v-slot="{row}">
              {{ row.formOfEmployment===1?'正式': '非正式' }}
            </template>
          </el-table-column>
          <el-table-column
            prop="departmentName"
            label="部门"
          />
          <el-table-column
            prop="timeOfEntry"
            label="入职时间"
            sortable
          />
          <el-table-column
            label="操作"
          >
            <template v-slot="{row}">
              <el-button size="mini" type="text" @click="getEmployeeDetail(row.id)">查看</el-button>
              <el-button size="mini" type="text" @click="btnRole(row.id)">角色</el-button>
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="del(row.id)"
              >
                <el-button slot="reference" size="mini" type="text" class="btn">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row type="flex" style="height:60px" align="middle" justify="end">
          <el-pagination
            layout="prev, pager, next"
            :current-page="queryParams.page"
            :page-size="queryParams.pagesize"
            :total="total"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <importExcel :show-excel-dialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList" />
    <el-dialog
      title="角色分配"
      :visible.sync="showRoleDialog"
      width="40%"
    >
      <el-checkbox-group v-model="roleIds">
        <el-checkbox
          v-for="item in roleList"
          :key="item.id"
          :label="item.id"
        >{{ item.name }}</el-checkbox>
      </el-checkbox-group>

      <el-row slot="footer" type="flex" justify="center" align="center">
        <el-button size="mini" type="primary" @click="assignRole">确 定</el-button>
        <el-button size="mini" @click="showRoleDialog = false">取 消</el-button>
      </el-row>

    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { zhuanghua } from '@/utils/index'
import { getEmployeeList, exportEmployee, remveEmployee, getEnableRoleList, assignRole, getEmployeeDetail } from '@/api/employee'

import FileSaver from 'file-saver'
import importExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    importExcel
  },
  data() {
    return {
      deups: [],
      defaultProps: {
        label: 'name'
      },
      queryParams: {
        page: 1,
        pagesize: 10,
        departmentId: null,
        keyword: ''
      },
      total: 0,
      list: [],
      showExcelDialog: false, // 员工导入的弹出层
      showRoleDialog: false, // 控制角色弹出层
      roleList: [], // 角色权限列表
      roleIds: [] // 用来角色双向绑定的值,被勾选的值就会添加进来 取消勾选就会踢出去
    }
  },
  async created() {
    this.getDepartment()
  },
  methods: {
    async getDepartment() {
      // 递归方法 将列表转化成树形
      // let result = await getDepartment()
      this.deups = zhuanghua(await getDepartment(), 0)
      // console.log(this.deups[0].id)
      this.queryParams.departmentId = this.deups[0].id
      // 设置选中节点
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        // 此时意味着树渲染完毕
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    selectNode(node) {
      this.queryParams.departmentId = node.id
      this.queryParams.page = 1
      this.getEmployeeList()
    },
    async getEmployeeList() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.list = rows
      this.total = total
    },
    changePage(newpage) {
      this.queryParams.page = newpage
      this.getEmployeeList()
    },
    input() {
      clearTimeout(this.timer)
      this.timer = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 500)
    },
    async exportEmployee() {
      const res = await exportEmployee()
      FileSaver.saveAs(res, '员工信息表.xlsx')
    },
    async del(id) {
      await remveEmployee(id)
      if (this.list.length === 1 && this.queryParams.page) this.queryParams.page-- // 玩够了记得打开
      this.getEmployeeList() // 记得打开
      // this.getEmployeeList()
    },
    addemployee() {
      this.$router.push('/employee/detail')
    },
    getEmployeeDetail(id) {
      this.$router.push(`/employee/detail/${id}`)
    },
    // 点击角色触发
    async btnRole(id) {
      // 调查询 获取可用角色
      this.roleList = await getEnableRoleList()
      // console.log(this.roleList)
      this.currentUserId = id
      const { roleIds } = await getEmployeeDetail(id)
      this.roleIds = roleIds
      this.showRoleDialog = true
    },
    async assignRole() {
      await assignRole({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.showRoleDialog = false
    }
    // ghs() {
    //   setInterval(() => {
    //     const n = Math.round(Math.random() * (this.list.length - 1)) + 1
    //     this.getEmployeeList()
    //     if (this.list[n]?.id) {
    //       console.log(this.list[n].id)
    //       this.del(this.list[n].id)
    //     }
    //   }, 50)
    // }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin:10px ;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display:inline-block;
    }
    .btn{
      margin-left: 10px;
    }
  }
}

</style>
